# -*— coding = utf-8 -*-
# @Time : 2022/1/7 17:21
# @Author : tacke
# @File : miui_down_2022_1.py
# @Software : PyCharm
import sys
import requests
from tqdm import tqdm
from lxml import html
etree = html.etree

def gethtml(url):
    headers = {
        "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        "Cookie": "",
        "Referer": "https://github.com",
    }
    r = requests.get(url, headers=headers)
    if r.status_code != 200:
        print("获取url：%s失败!" % (url))
        exit()
    return r


def getxpath(r, str):
    html = etree.HTML(r.text)
    reslist = html.xpath(str)
    return reslist


def get_d_one_url_txt():
    if ban_b == '1':
        edition = 'CN_BETA'
    elif ban_b == '2':
        edition = 'GB_BETA'
    elif ban_b == '3':
        edition = 'CN_STABLE'
    elif ban_b == '4':
        edition = 'GB_STABLE'
    url = "https://roms.miuier.com/devices/"
    url = url + device + '#' + edition
    r = gethtml(url)

    data = etree.HTML(r.text)
    # recovery packages
    if edition == 'CN_STABLE' and type_package == '1':
        tr = data.xpath('/html/body/div[6]/div/table/tbody/tr')
        link = './/td[4]/a/@href'
    elif edition == 'CN_BETA' and type_package == '1':
        tr = data.xpath('/html/body/div[4]/div/table/tbody/tr')
        link = './/td[5]/a/@href'
    elif edition == 'GB_STABLE' and type_package == '1':
        tr = data.xpath('/html/body/div[7]/div/table/tbody/tr')
        link = './/td[4]/a/@href'
    elif edition == 'GB_BETA' and type_package == '1':
        tr = data.xpath('/html/body/div[5]/div/table/tbody/tr')
        link = './/td[5]/a/@href'
    # fastboot packages
    elif edition == 'CN_STABLE' and type_package == '2':
        tr = data.xpath('/html/body/div[6]/div/table/tbody/tr')
        link = './/td[5]/a/@href'
    elif edition == 'CN_BETA' and type_package == '2':
        tr = data.xpath('/html/body/div[4]/div/table/tbody/tr')
        link = './/td[6]/a/@href'
    elif edition == 'GB_STABLE' and type_package == '2':
        tr = data.xpath('/html/body/div[7]/div/table/tbody/tr')
        link = './/td[5]/a/@href'
    elif edition == 'GB_BETA' and type_package == '2':
        tr = data.xpath('/html/body/div[5]/div/table/tbody/tr')
        link = './/td[6]/a/@href'

    # 循环遍历链接
    for tr in tr:
        try:
            d_url_list = tr.xpath(link)
            print(d_url_list[0])
        except IndexError:  # 空列表报错解决
            pass


# showing models
def show_device_txt():
    try:
        url = "https://github.com/mooseIre/update_miui_ota/blob/master/README.md"
        r = gethtml(url)

        data = etree.HTML(r.text)
        td = data.xpath('//*[@id="readme"]/article/table/tbody/tr')

        # 循环遍历支持的device
        for tr in td:
            d_url_list = tr.xpath(".//td[1]/text()")
            print(d_url_list[0])
    except:
        show_device_txt()


def r_other_py():
    # 第一步：请求网址先获取html
    try:  # 使用try-except防止被源站识别为攻击
        if ban_b == '1':
            edition = 'Develop'
        elif ban_b == '2':
            edition = 'Stable'
        url = "https://github.com/mooseIre/update_miui_ota/blob/master/"
        url = url + edition + '/' + device + '.md'
        r = gethtml(url)

        data = etree.HTML(r.text)
        a = data.xpath('//*[@id="readme"]/article/table/tbody/tr')

        # 循环遍历选定链接
        for tr in a:
            d_url_list = tr.xpath(".//td/a/@href")
            print(d_url_list[0])
    except:
        r_other_py()


# 下载区
def download_rom():
    url = d_url
    res = requests.get(url, stream=True)
    file_size = int(res.headers.get('Content-Length'))  # 获取文件的总大小
    file_size_MB = int(file_size / 1048576)  # 转换存储大小单位为MB
    print('the size of package is：' + str(file_size_MB) + ' MB')
    print("##############-------------------Download Ready-----------------#############")
    pbar = tqdm(total=file_size)  # 设置进度条的长度
    if type_package == '1':
        down_path = './recovery_update.zip'
    elif type_package == '2':
        down_path = './fast_boot.tgz'
    with open(down_path, 'wb') as f:
        for chunk in res.iter_content(1024 * 1024 * 2):
            f.write(chunk)
            pbar.set_description('Downloading......')
            pbar.update(1024 * 1024 * 2)  # 更新进度条长度
        pbar.close()


if __name__ == '__main__':
    device = input("请输入要检索的型号：")
    ban_b = input("请输入要使用的版本序号(1.大陆开发版、2.国际开发版、3.大陆稳定版、4.国际稳定版)：")
    if ban_b == '1':
        pass
    elif ban_b == '2':
        pass
    elif ban_b == '3':
        pass
    elif ban_b == '4':
        pass
    else:
        print("#===================别调皮了，快输入正确的序号！======================#")
        sys.exit()
    type_package = input("刷机包类型？(1.卡刷包、2.线刷包)：")
    get_d_one_url_txt()
    print("")
    print("是否获取到链接信息？")
    if input("yes or no? ：") == 'no':
        print("#=====================此爬虫仅支持卡刷包!!!==============================#")
        print("")
        print("Currently, the following models are supported (directly copy the listed target models for retrieval)：")
        print("#=====================================================================================================#")
        print("")
        show_device_txt()
        device = input("请输入要检索的机型：")
        ban_b = input("请输入要使用的版本序号(1.大陆开发版、2.大陆稳定版)：")
        r_other_py()
    else:
        if input("想直接下载刷机包吗？（yes or no?）：") == 'yes':
            d_url = input("复制链接粘贴下载：")
            download_rom()
        else:
            sys.exit()
